package algorithm.math;

/**
 * leetcode : https://leetcode.com/problems/reverse-integer/description/
 * Difficulty : Easy
 *
 * 对边界值的控制，参考 Integer.parseInt
 * 因为负数的极限值绝对值比正数大，
 * 因此，如果是正数，转为负数。按负数来计算并校验边界值
 * 最后在结果再转回原来的正负号
 *
 * @Author Antony
 * @Since 2018/7/13 23:50
 */
public class ReverseInteger {

    public static void main(String[] args) {
        int a = -123;
        System.out.println(reverse(a));
    }

    /**
     * beats 98.56% - 22ms
     */
    public static int reverse(int x) {
        boolean negative = false;
        int limit = Integer.MIN_VALUE;
        if(x > 0){
            x = -x;
            negative = true;
            limit = -Integer.MAX_VALUE;
        }
        int multMin = limit/10;
        int num = 0;
        while(x != 0){
            if(num < multMin){
                return 0;
            }
            num = num*10 + x%10;
            x = x/10;
        }

        return negative ? -num : num;
    }
}
